package com.zhongcw.tool.kuaichuan.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器
 */
public class Server_3 extends ServerSocket {

    private static final int PORT = 2013;

    private ServerSocket server;
    private Socket client;
    private FileOutputStream fos;
    BufferedInputStream buf;

    public Server_3() throws Exception {
        try {
            try {
                server = new ServerSocket(PORT);

                System.out.println("开始监听。。。");
                client = server.accept();

                System.out.println("连接成功。。。");
                 buf=new BufferedInputStream(client.getInputStream());

                fos = new FileOutputStream(new File("d:/tempfile/" + "Server_"+""));

                byte[] sendBytes = new byte[(int)Math.pow(1024D,2D)*100];
                System.out.println("----开始接收文件<" + ">----");

                long transLen = 0;
                int read = 0;
                int i = 0;
                while ((read = buf.read(sendBytes))>0) {
                    transLen += read;
                    System.out.println("接收文件进度" + transLen + "%...");
                    fos.write(sendBytes);
                    fos.flush();
                    i++;
                }

                System.out.println("该文件分为 "+i+" 发送");
                System.out.println("----接收文件<" +  ">成功-------");
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (buf != null)
                    buf.close();
                if (fos != null)
                    fos.close();
                server.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        new Server_3();
    }
}